package br.edu.universo.si.projeto2.infojob.client.apresentacao;

import br.edu.universo.si.projeto2.infojob.client.bean.BeanEmpresaAssinante;
import br.edu.universo.si.projeto2.infojob.client.bean.BeanEstado;
import br.edu.universo.si.projeto2.infojob.client.componentes.CEPBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.CNPJBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.CPFBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.EMailBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.NumberBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.comboboxes.EstadosListBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.dialogboxes.ErrorDialogBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.dialogboxes.InformationDialogBox;
import br.edu.universo.si.projeto2.infojob.client.componentes.dialogboxes.SuccessDialogBox;
import br.edu.universo.si.projeto2.infojob.client.util.Util;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class ACadastroEmpresa extends DockPanel
{
	private FlexTable flexTable;
	private HorizontalPanel rodape;

	private Button cadastrarBtn;
	private Button cancelarBtn;

	private CNPJBox cnpjTxt;
	private TextBox razaoSocialTxt;
	private TextBox responsavelTxt;
	private NumberBox telefoneTxt;
	private EMailBox emailTxt;
	private CPFBox cpfResponsavelTxt;
	private NumberBox rgResponsavelTxt;
	private CEPBox cepTxt;
	private TextBox enderecoTxt;
	private NumberBox numeroTxt;
	private TextBox bairroTxt;
	private TextBox complementoTxt;
	private TextBox cidadeTxt;
	private TextBox contaTxt;
	private PasswordTextBox senhaTxt;
	private EstadosListBox estadosListBox;
	
	public ACadastroEmpresa()
	{
		inicializarComponentes();

		flexTable.setCellSpacing(5);

		rodape.setSpacing(3);

		// seta os tamanhos dos campos...
		razaoSocialTxt.setWidth("300px");
		responsavelTxt.setWidth("300px");
		telefoneTxt.setWidth("100px");
		telefoneTxt.setMaxLength(16);
		rgResponsavelTxt.setWidth("100px");
		rgResponsavelTxt.setMaxLength(10);
		enderecoTxt.setWidth("300px");
		enderecoTxt.setMaxLength(40);
		numeroTxt.setWidth("50px");
		numeroTxt.setMaxLength(5);
		bairroTxt.setWidth("100px");
		bairroTxt.setMaxLength(20);
		complementoTxt.setWidth("300px");
		complementoTxt.setMaxLength(30);
		cidadeTxt.setWidth("100px");	
		cidadeTxt.setMaxLength(15);
		contaTxt.setWidth("120px");
		contaTxt.setMaxLength(20);
		senhaTxt.setWidth("120px");
		senhaTxt.setMaxLength(20);

		flexTable.setWidget(0, 0, new HTML("Cadastro de Empresa"));
		flexTable.getFlexCellFormatter().setColSpan(0, 0, 2);
		flexTable.getFlexCellFormatter().setStyleName(0, 0, "tituloFormCadastro");

		flexTable.setWidget(1, 0, new HTML("<b>* Razão Social</b> "));
		flexTable.setWidget(1, 1, razaoSocialTxt);
		flexTable.getFlexCellFormatter().setAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(2, 0, new HTML("<b>* CNPJ:</b> "));
		flexTable.setWidget(2, 1, cnpjTxt);
		flexTable.getFlexCellFormatter().setAlignment(2, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(3, 0, new HTML("Responsável: "));
		flexTable.setWidget(3, 1, responsavelTxt);
		flexTable.getFlexCellFormatter().setAlignment(3, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(4, 0, new HTML("Telefone: "));
		flexTable.setWidget(4, 1, telefoneTxt);
		flexTable.getFlexCellFormatter().setAlignment(4, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(5, 0, new HTML("E-Mail: "));
		flexTable.setWidget(5, 1, emailTxt);
		flexTable.getFlexCellFormatter().setAlignment(5, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(6, 0, new HTML("CPF do Responsável: "));
		flexTable.setWidget(6, 1, cpfResponsavelTxt);
		flexTable.getFlexCellFormatter().setAlignment(6, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(7, 0, new HTML("RG do Responsável: "));
		flexTable.setWidget(7, 1, rgResponsavelTxt);
		flexTable.getFlexCellFormatter().setAlignment(7, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(8, 0, new HTML("CEP: "));
		flexTable.setWidget(8, 1, cepTxt);
		flexTable.getFlexCellFormatter().setAlignment(8, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(9, 0, new HTML("Endereço: "));
		flexTable.setWidget(9, 1, enderecoTxt);
		flexTable.getFlexCellFormatter().setAlignment(9, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(10, 0, new HTML("Número: "));
		flexTable.setWidget(10, 1, numeroTxt);
		flexTable.getFlexCellFormatter().setAlignment(10, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(11, 0, new HTML("Bairro: "));
		flexTable.setWidget(11, 1, bairroTxt);
		flexTable.getFlexCellFormatter().setAlignment(11, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(12, 0, new HTML("Complemento: "));
		flexTable.setWidget(12, 1, complementoTxt);
		flexTable.getFlexCellFormatter().setAlignment(12, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(13, 0, new HTML("Cidade: "));
		flexTable.setWidget(13, 1, cidadeTxt);
		flexTable.getFlexCellFormatter().setAlignment(13, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(14, 0, new HTML("Escolha o estado: "));
		flexTable.setWidget(14, 1, estadosListBox);
		flexTable.getFlexCellFormatter().setAlignment(14, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(15, 0, new HTML("<b>* Conta: </b>"));
		flexTable.setWidget(15, 1, contaTxt);
		flexTable.getFlexCellFormatter().setAlignment(15, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);

		flexTable.setWidget(16, 0, new HTML("<b>* Senha: </b>"));
		flexTable.setWidget(16, 1, senhaTxt);
		flexTable.getFlexCellFormatter().setAlignment(16, 0, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_MIDDLE);
		
		rodape.add(cadastrarBtn);
		rodape.add(cancelarBtn);

		flexTable.setWidget(17, 0, rodape);
		flexTable.getFlexCellFormatter().setColSpan(17, 0, 2);
		flexTable.getFlexCellFormatter().setAlignment(17, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);

		this.add(flexTable, DockPanel.CENTER);

		// CADASTRAR EMPRESA
		cadastrarBtn.addClickListener(
				new ClickListener()
				{
					public void onClick(Widget sender)
					{
						BeanEmpresaAssinante bEmpresaAssinante = new BeanEmpresaAssinante();

						bEmpresaAssinante.setCnpj(cnpjTxt.getText());
						bEmpresaAssinante.setRazaoSocial(razaoSocialTxt.getText());
						bEmpresaAssinante.setResponsavel(responsavelTxt.getText());
						bEmpresaAssinante.setTelefone(telefoneTxt.getText());
						bEmpresaAssinante.setEmail(emailTxt.getText());
						bEmpresaAssinante.setCpfResponsavel(cpfResponsavelTxt.getText());
						bEmpresaAssinante.setRgResponsavel(rgResponsavelTxt.getText());
						bEmpresaAssinante.setEndereco(enderecoTxt.getText());
						bEmpresaAssinante.setNumero(numeroTxt.getText());
						bEmpresaAssinante.setBairro(bairroTxt.getText());
						bEmpresaAssinante.setComplemento(complementoTxt.getText());
						bEmpresaAssinante.setCidade(cidadeTxt.getText());

						BeanEstado bEstado = new BeanEstado();
						bEstado.setId(estadosListBox.getValue(estadosListBox.getSelectedIndex()));
						bEstado.setEstado(estadosListBox.getItemText(estadosListBox.getSelectedIndex()));

						bEmpresaAssinante.setBEstado(bEstado);
						bEmpresaAssinante.setCep(cepTxt.getText());
						bEmpresaAssinante.setConta(contaTxt.getText());
						bEmpresaAssinante.setSenha(senhaTxt.getText());

						AsyncCallback<Object> callback = new AsyncCallback<Object>()
						{
							public void onSuccess(Object result)
							{
								limparCampos(); // limpa os campos

								SuccessDialogBox successDialobBox = new SuccessDialogBox("Empresa cadastrada com sucesso.", 
										new SuccessDialogBox.SuccessCallback()
										{
											public void execute()
											{
												RootPanel.get().remove(ACadastroEmpresa.this);
												RootPanel.get().add(new APrincipal());
											}
										}
								);
								successDialobBox.center();
								successDialobBox.show();
							};

							public void onFailure(Throwable caught)
							{
								ErrorDialogBox errorDialogBox = new ErrorDialogBox("Erro ao cadastrar Empresa: " + caught.getMessage());
								errorDialogBox.center();
								errorDialogBox.show();
							};
						};

						// se todos os campos estiverem ok, invoca o RPC para cadastrar a Empresa no banco
						if (verificarCampos())
						{
							Util.getService().cadastrarEmpresaAssinante(bEmpresaAssinante, callback);							
						}
						
					}
				}
		);
		
		// CANCELAR CADASTRO
		cancelarBtn.addClickListener(
			new ClickListener()
			{
				public void onClick(Widget sender)
				{
					RootPanel.get().remove(ACadastroEmpresa.this);
					RootPanel.get().add(new APrincipal());
				}
			}
		);
	}
	
	private void inicializarComponentes()
	{
		flexTable = new FlexTable();

		rodape = new HorizontalPanel();

		cadastrarBtn = new Button("Cadastrar");
		cancelarBtn = new Button("Cancelar");
		
		cnpjTxt = new CNPJBox();
		razaoSocialTxt = new TextBox();
		responsavelTxt = new TextBox();
		telefoneTxt = new NumberBox();
		emailTxt = new EMailBox();
		cpfResponsavelTxt = new CPFBox();
		rgResponsavelTxt = new NumberBox();
		cepTxt = new CEPBox();
		enderecoTxt = new TextBox();
		numeroTxt = new NumberBox(200);
		bairroTxt = new TextBox();
		complementoTxt = new TextBox();
		cidadeTxt = new TextBox();
		contaTxt = new TextBox();
		senhaTxt = new PasswordTextBox();
		estadosListBox = new EstadosListBox();
	}
	
	private boolean verificarCampos()
	{
		// verifica se campos obrigatorios estao preenchidos
		
		if (razaoSocialTxt.getText().equalsIgnoreCase(""))
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("Campo 'razão social' não preenchido.");
			infoDialogBox.center();
			infoDialogBox.show();
			
			return false;
		}

		if (cnpjTxt.isVazio())
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("Campo 'cnpj' não preenchido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;
		}
		
		if (!cnpjTxt.isCNPJValido())
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("CNPJ inválido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;			
		}

		if (contaTxt.getText().equalsIgnoreCase(""))
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("Campo 'conta' não preenchido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;			
		}

		if (senhaTxt.getText().equalsIgnoreCase(""))
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("Campo 'senha' não preenchido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;			
		}
		
		if (senhaTxt.getText().length() < 6)
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("A senha deve ter no mínimo 6 caracteres.");
			infoDialogBox.center();
			infoDialogBox.show();
			
			senhaTxt.setText("");

			return false;			
		}

		// verifica se o email eh valido
		if (!emailTxt.isVazio() && !emailTxt.isEMailValido())
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("E-Mail inválido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;
		}

		if (!cpfResponsavelTxt.isVazio() && !cpfResponsavelTxt.isCPFValido())
		{
			InformationDialogBox infoDialogBox = new InformationDialogBox("CPF inválido.");
			infoDialogBox.center();
			infoDialogBox.show();

			return false;			
		}

		return true;
	}

	private void limparCampos()
	{
		cnpjTxt.setText("");
		razaoSocialTxt.setText("");
		responsavelTxt.setText("");
		telefoneTxt.setText("");
		emailTxt.setText("");
		cpfResponsavelTxt.setText("");
		rgResponsavelTxt.setText("");
		cepTxt.setText("");
		enderecoTxt.setText("");
		numeroTxt.setText("");
		bairroTxt.setText("");
		complementoTxt.setText("");
		cidadeTxt.setText("");
		contaTxt.setText("");
		senhaTxt.setText("");
	}
}